# coding: utf-8
import tfct.ply.lex as lex
import tfct.ply.yacc as yacc
import re 

class TDLParser:
    tokens = (  
                  'WORD',
                  'IDENT',
                  'TESTTAG',
                  'EQUAL' ,
                  'TITLE'                 
                   )

    literals = ['=','+','-','*','/', '(',')',':','.','[',']','"']
    #token definitions          
    t_IDENT       = r'[A-Za-z][A-Za-z0-9_]*\.'    
    t_WORD        = r'[A-Za-z][A-Za-z0-9_]*'       
    t_TITLE       = r'[A-Za-z0-9\ ]+\n'       
    t_TESTTAG     = r'[A-Z]{2}[0-9]+\.[0-9]+\([A-Za-z0-9]+\):'
    t_EQUAL       = r'[A-Za-z]+="[A-Za-z0-9]+"'

    t_ignore = " \t"

    def t_newline(self,t):
        r'\n+'
        t.lexer.lineno += t.value.count("\n")

    def t_error(self,t):
        print("Illegal character '%s'" % t.value[0])
        #t.lexer.skip(1)
        
        #yacc rules
    def p_testcases(self,p):
        '''TESTCASES : TESTCASE 
                 | TESTCASES TESTCASE'''
    def p_p_testcase(self,p):
        'TESTCASE : WORD IDENT WORD PRECONDITIONS TESTSTEPS'
        #tworzymy test case
        id = re.findall(r'\d+', p[2])
        testcase = self.tdl.add_testcase(int(id[0]), p[3])
        
        #dodajemy predoncidions
        #if(p[4] != None):
            #condition = model.Condition({},p[4])
            
            #niezaimplementowane bo trzeba przekazac caly obiekt TC, ktorego w tej chwili nie posiadam
            
        #dodajemy kroki testu
        for step in self.teststeps:
            tc = testcase.add_step(step[0], step[1])
        
            #dodajemy wszystkie akcje
            for action in step[2]:
                reg = re.findall(r'([A-Za-z][A-Za-z0-9]*)="(.*)"',action[1])
                if (len(reg[0]) == 2): # oznacza ze mamy cos z wartoscia = ""
                    tc.add_action(action[0], reg[0][0], reg[0][1])
                else:
                    reg = re.findall(r'([A-Za-z][A-Za-z0-9]*)',action[1])
                    if(len(reg[0]) == 2): #reszta
                        tc.add_action(action[0], reg[0][0], reg[0][1])
                    
            self.actions = list()
        self.teststeps = list()

    def p_preconditions(self,p):
        # PRECONDITIONS
        # PRECONDITIONS TC1_2
        '''PRECONDITIONS : WORD WORD 
                       | WORD'''   
        if(len(p) == 3):
            p[0] = p[2]
            
    
    def p_teststeps(self,p):
        '''TESTSTEPS : TESTSTEP
                     | TESTSTEP TESTSTEPS'''
   
    def p_teststep(self,p):
        """TESTSTEP : WORD TESTTAG ACTIONS"""
        found = re.findall('(\d+\.\d+)\(([A-Za-z]+)\)',p[2])
        # ID , NAME, list of actions 
        self.teststeps.append([found[0][0], found[0][1],self.actions])
        self.actions = list()
    
    def p_actions(self,p):
        """ACTIONS : ACTIONS CLICK
                   | CLICK
                   | ACTIONS SET
                   | SET """ 
        
        if (len(p) == 2):  # CLICK, SET
            self.actions.append(p[1])
        elif (len(p) == 3):  # ACTION ....
            self.actions.append(p[2])
            
    def p_click(self,p):
        "CLICK : WORD WORD"    
    def p_set(self,p):
        "SET : WORD EQUAL"
        p[0] =  [p[1],p[2]]

    
    def p_error(self,p):
        if p:
            print("Syntax error at '%s'" % p)
        else:
            print("Syntax error at EOF")

    def __init__(self, conf):
        self.lexer = lex.lex(module=self)
        self.yacc = yacc.yacc(module=self)
        self.conf = conf
        self.actions = list()
        self.teststeps = list()
    
    def run_file(self, filename):
        f = open(filename, 'r')
        return self.run_text(f.read())
    
    def run_text(self, text):        
        self.yacc.parse(text)
        
        return self.tdl;